import React from 'react';
import { connect } from 'dva';
import { createForm } from 'rc-form';
import cx from 'classnames';
import { WingBlank, WhiteSpace, Flex, List, Button, Toast } from 'antd-mobile';
import { Link, routerRedux } from 'dva/router';
import styles from '../scale/styles.less';
import { SCALE_DIA, SCALE_DIA_C, SCALE_DIA_ITEM } from 'const';

Array.prototype.unique2 = function(){
 this.sort(); //先排序
 var res = [this[0]];
 for(var i = 1; i < this.length; i++){
  if(this[i] !== res[res.length - 1]){
   res.push(this[i]);
  }
 }
 return res;
}
function ScaleTemplate({ dispatch, location, form, scalevalue, detail, ...rest }) {
  let questions;
  const { state, query } = location;
  const { type, patientid, step, patientvalue } = location.state;
  const { getFieldProps, getFieldValue, setFieldsValue, validateFields, getFieldError } = form;
  let maxstep = 13;
  if(state.gender == 1){
      questions = SCALE_DIA_C;
  }else{
      questions = SCALE_DIA;
  }

  let question = questions[step];

  let nextStep = step + 1;
  const category = step - 1;
  let scores = scalevalue[0] || [];
   for(var z =0;z<scores.length;z++){
     for(var j= z+1; j<scores.length;j++){
      if(scores[z]== scores[j]){
        scores.splice(z,1);
        z--;
      }
     }
  }

  let canNotSelect = scalevalue[1] || [];
  let title = '';
  if (step === 1) {
    title = '完善用户信息';
  }

  let stepQuestions = [];
  if (category >= 0 && category < maxstep) {
    stepQuestions = questions[category].subject;
    title = questions[category].title;
  }

  const validateForm = () => {

    validateFields((err, values) => {
      if (err) {
        const fieldNames = Object.keys(err);
        if (fieldNames[0]) {
          return Toast.fail(getFieldError(fieldNames[0]));
        }
      } else {
          Object.keys(values).forEach((key) => {
            if (values[key]) {
              scores.push(key);
            } 
          });
        dispatch({ type: 'scale/save', payload: { scalevalue: [ scores, canNotSelect] } });

        if (nextStep <= maxstep) {
          let pathname = location.pathname;
          dispatch(
            routerRedux.replace({
              pathname,
              state: {
                type,
                patientid,
                step: nextStep,
                gender: state.gender
              },
            }),
          );
        } else {
          // 最后一页'提交'
          scores = scores.unique2();
          if(scores.length < 5){
            Toast.fail('选择的症状信息过少，请重新选择');
          }else{
            const patientValue = scores.join(',');
            dispatch({
              type: 'scale/submitQuestions',
              payload: {
                type: 'dia',
                patientId: state.patientid,
                familyId: JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId,
                patientValue,
                ...rest,
              },
            });
          }
        }
      }
    });
  };
   function isDisable(name, value, i){      
    if (Array.from(canNotSelect).find(item => item === name)) {
      return true;
    }

    return false;
  }
  function isActive(key, value, i,ponent) {

    if (Array.from(scores).find(item => item === key)) {
      return true;
    }

    if (!getFieldValue(key)) {
      return false;
    }

    return getFieldValue(key) === value;
  }

  function handleChange({ target: { type, name, value } }) {
     if (Array.from(canNotSelect).find(item => item === name)) {
          return;
        }

        if (Array.from(scores).find(item => item === name)) {
          setFieldsValue({ [name]: value }); //form实际值与状态不符，用赋值保持相符
          scores = Array.from(scores).filter(item => item !== name); //从scores中去除
        }
        if (getFieldValue(name) === value) {
          setFieldsValue({ [name]: null });

          const items = SCALE_DIA_ITEM[name];

          if(items){
             items.split(';').forEach((item, i) => {
              if (canNotSelect.find(one => one === item)) {
                canNotSelect = canNotSelect.filter(one => one !== item);
            
              }
            });
              Array.from(scores).forEach((item, i) => {
                  const items = SCALE_DIA_ITEM[item];
                  if (items) {
                    items.split(';').forEach((item, i) => {
                      if (!canNotSelect.find(one => one === item)) {
                        canNotSelect.push(item);
                      }
                    });
                  }
                });
              validateFields((err, values) => {
                  Object.keys(values).forEach((key) => {
                    if (values[key]) {
                      const items = SCALE_DIA_ITEM[key];
                      if (items) {
                        items.split(';').forEach((item, i) => {
                          if (!canNotSelect.find(one => one === item)) {
                            canNotSelect.push(item);
                          }
                        });
                      }
                    }
                  });
                });
          }
        } else {
          setFieldsValue({ [name]: value });
          const items = SCALE_DIA_ITEM[name];
          if (items) {
            items.split(';').forEach((item, i) => {
              if (!canNotSelect.find(one => one === item)) {
                canNotSelect.push(item);
             
              }
            });
          }
        }
       
        dispatch({ type: 'scale/save', payload: { scalevalue: [scores, canNotSelect] } });
  }

  function nextHandler() {
    document.body.scrollTop = document.documentElement.scrollTop = 0
    nextStep = step + 1;
    validateForm();
  }

  function prevHandler() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    nextStep = step - 1;
    validateForm();
  }
  
  function submitHandler() {
    nextStep = step + 1;
    validateForm();
  }

  return (
    <WingBlank size="md">
      <WhiteSpace />
      <List>
        <List.Item>
          <Flex justify="center">{`${step}/${maxstep} ${title || detail.Title}`}</Flex>
          <Flex justify="center" style={{marginTop: '0.1rem'}}>在近3个月内您是否频繁出现以下症状</Flex>
          <Flex justify="center">（有则选, 无可跳过, 也可以多选）</Flex>
        </List.Item>
          {stepQuestions.map((question, i) => (
            <List.Item wrap multipleLine key={question.id}>
              {`${i + 1}. ${question.title}`}
              <List.Item.Brief>
                <Flex wrap="wrap" className={styles.questionOptions}>
                  {question.item.map((option, i) => {
                    const key = option.id;
                    const value = option.title;
                    const ponent = option.ponent;
                    return (
                      <label key={key} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i, ponent),[styles.questionOptionDisable]: isDisable(key, value, i, ponent), })}>
                        <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value}   checked={isActive(key, value, i)} onChange={handleChange} />
                        {value}
                      </label>
                    );
                  })}
                </Flex>
              </List.Item.Brief>
            </List.Item>
          ))}
        <div>
          <WhiteSpace size="xl" />
          <WingBlank>
            <Flex>
              {step === 1
                ? null
                : <Flex.Item>
                  <Button onClick={prevHandler}>上一页</Button>
                </Flex.Item>}

              {step < maxstep
                ? <Flex.Item>
                  <Button type="primary" onClick={nextHandler}>下一页</Button>
                </Flex.Item>
                : <Flex.Item>
                  <Button type="primary" onClick={submitHandler}>提交</Button>
                </Flex.Item>}

            </Flex>
          </WingBlank>
          <WhiteSpace size="xl" />
        </div>
      </List>
      <WhiteSpace size="xl" />
    </WingBlank>
  );
}

export default connect(({ scale }) => ({ ...scale }))(createForm()(ScaleTemplate));
